<template>
    <div class="container flex-r-center">
        <span class="text" id="text"></span>
        <span class="cursor"></span>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const textList = [
  'No pains, no gains',
  '不劳无获',
  // 可以在这里添加更多的文本
];
const currentTextIndex = ref(0);
const currentText = ref(textList[currentTextIndex.value]);
const addTimeinterval = 150; // 每 150 毫秒添加一个字符
const rmTimeinterval = 60; // 每 60 毫秒删除一个字符
const addPauseDuration = 3000; // 每个句子添加完整之后停留的时长
const rmPauseDuration = 1000; // 每个句子删除完之后停留的时长

let timeoutId;

/**
 * 模拟打字机效果的函数
 *
 * @param index 当前要显示的字符的索引
 * @param total 总共要显示的字符数
 */
function typeWriter(target, index, total) {
  if (index <= currentText.value.length) { // 添加字符
    target.innerHTML = currentText.value.substring(0, index);
    const interval = index === currentText.value.length ? addPauseDuration : addTimeinterval;
    index++;
    timeoutId = setTimeout(() => typeWriter(target, index, total), interval);
  } else { // 删除字符
    if (total >= 0) {
      target.innerHTML = currentText.value.substring(0, total);
      const interval = total === 0 ? rmPauseDuration : rmTimeinterval;
      total--;
      timeoutId = setTimeout(() => typeWriter(target, index, total), interval);
    } else {
      currentTextIndex.value = (currentTextIndex.value + 1) % textList.length;
      currentText.value = textList[currentTextIndex.value];
      typeWriter(target, 1, currentText.value.length)
    }
  }
}

onMounted(() => {
  let span = document.getElementById('text');
  typeWriter(span, 1, currentText.value.length);
});

onUnmounted(() => {
  clearTimeout(timeoutId);
});
</script>

<style lang="scss" scoped>
.container {
  color: var(--header-text-color);
  // background-color: orchid;

  .text {
    display: inline-block;
    font-size: 24px;
    height: 20px;
    font-weight: 500;
    // background-color: plum;
  }

  .cursor {
    margin-left: 5px;
    margin-bottom: -20px;
    width: 3px;
    height: 20px;
    animation: blink 1s step-end infinite;
    background-color: var(--header-text-color);
  }

  @keyframes blink {
    50% {
      opacity: 0;
    }
  }
}
</style>